package man4j;

import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;

public class GoScreen extends List implements CommandListener {
	public static final String GO = "GO!";
	
	private Command backCommand;
	
	private MainMIDlet mainMIDlet;
	
	private Vector pendingTasks = new Vector();
	
	private Image completeImage, incompleteImage;
	
	public GoScreen(final MainMIDlet mainMIDlet) {
		super(GO, List.IMPLICIT);
		
		this.mainMIDlet = mainMIDlet;
		
		backCommand = new Command("Back", Command.BACK, 1);
		
		addCommand(backCommand);
		
		setCommandListener(this);
		
		try { 
			int h = Display.getDisplay(mainMIDlet).getBestImageHeight(Display.LIST_ELEMENT);
			
			completeImage = ImageUtils.resizeImage(Image.createImage(getClass().getResourceAsStream("/complete.png")), h, h);
			incompleteImage = ImageUtils.resizeImage(Image.createImage(getClass().getResourceAsStream("/incomplete.png")), h, h);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
	public void saveTasks() {
		TaskStore.saveTasks(CurrentTaskScreen.class.getName(), pendingTasks);
	}

	public void commandAction(Command c, Displayable d) {
		if (c == backCommand) {
			saveTasks();
			
			Display.getDisplay(mainMIDlet).setCurrent(mainMIDlet.getMainScreen());			
		}		
		
		if (c == SELECT_COMMAND) {
		    int idx = getSelectedIndex();
			
			Task t = (Task) pendingTasks.elementAt(idx);
			
			pendingTasks.removeElementAt(idx);			
			delete(idx);
			
			int completeIdx = getFirstCompleteIndex();
			
			pendingTasks.insertElementAt(t, completeIdx);			
			insert(completeIdx, t.getString(), t.isComplete() ? incompleteImage : completeImage);			
			
			t.setComplete(!t.isComplete());
		}
	}
	
	public void update() {
		deleteAll();
		
		for (int i = 0; i < pendingTasks.size(); i++) {
			Task t = (Task) pendingTasks.elementAt(i);
			
			append(t.getString(), t.isComplete() ? completeImage : incompleteImage);
		}
	}
	
	void deleteTasks() {
		deleteAll();
		
		pendingTasks.removeAllElements();
	}
	
	void addTask(Task t) {
		pendingTasks.insertElementAt(t, getFirstCompleteIndex());
	}
	
	void deleteTask(Task editableTask) {
		pendingTasks.removeElement(editableTask);
	}
	
	private int getFirstCompleteIndex() {
		for (int i = 0; i < pendingTasks.size(); i++) {
			if (((Task)pendingTasks.elementAt(i)).isComplete()) {
				return i;
			}
		}
		
		return pendingTasks.size();
	}	
}
